package li.com.springaidemo.service.impl;

import ch.qos.logback.core.util.StringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import li.com.springaidemo.exception.CustomException;
import li.com.springaidemo.exception.GlobalExceptionHandler;
import li.com.springaidemo.mapper.HistoryMapper;
import li.com.springaidemo.pojo.History;
import li.com.springaidemo.pojo.Persona;
import li.com.springaidemo.service.HistoryService;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class HistoryServiceImpl extends ServiceImpl<HistoryMapper, History> implements HistoryService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    //    收集用户发送的信息
    @Override
    public List<Message> getMessages(String id,String message, List<Message> messages) {
//        用户发送的信息
        Message userMessage = new UserMessage(message);
//        人物设定
        String description = (String) redisTemplate.opsForValue().get("history"+id);

        if(StringUtil.isNullOrEmpty(description)){
            History history = this.getById(id);
            if(history==null){
                throw new CustomException("虚拟角色不存在");
            }
            if(history.getState()==0){
                throw new CustomException("虚拟角色已被禁用");
            }
            redisTemplate.opsForValue().set("history"+id,"你的性别是"+history.getSex()+"性。"+history.getDescription());
        }
        Message systemMessage = new SystemMessage(description);
        // 如果未获取到消息，则创建新的消息并将系统提示和用户输入的消息添加到消息列表中
        if (messages == null){
            messages = new ArrayList<>();
            messages.add(systemMessage);
            messages.add(userMessage);
        } else {
            messages.add(userMessage);
        }
        if (messages.size()>=10){
            messages.remove(1);
            messages.remove(2);
        }
        return messages;
    }
    //    收集AI返回的信息，与收集用户发送的信息同时进行
    @Override
    public List<Message> responseMessages(String objectName, ChatResponse chatResponse, List<Message> chatMessage) {
        AssistantMessage output = chatResponse.getResult().getOutput();
        chatMessage.add(output);
        if (chatMessage.size()>=10){
            chatMessage.remove(1);
            chatMessage.remove(2);
        }
        return chatMessage;
    }
}
